use socket2::{Domain, Socket, Type};
use std::mem::MaybeUninit;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::sync::{Arc, Mutex};
pub fn create_listener(port: u16) -> Socket {
    let socket = Socket::new(Domain::IPV4, Type::STREAM, None).expect("创建Socket失败!");
    let address: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port);
    socket.bind(&address.into()).expect("bind 失败！");
    let _ = socket.listen(128);
    socket
}

pub fn service(receiver: Socket, my_client_pool: Arc<Mutex<Vec<Socket>>>) {
    receiver
        .set_read_timeout(None)
        .expect("time out set error!");
    //socket 读写分离
    let socket_box = make_socket_split(receiver);
    let read = socket_box.0;
    // let write = socket_box.1;
    //创建新线程  用户信息的转发
    let t1 = std::thread::spawn(move || loop {
        let msg: Vec<u8> = recv_u8(&read);
        let size = my_client_pool.lock().unwrap().len();
        for index in 0..size {
            let local_ip = get_ip_str_from_socket(&read);
            let this_ip = get_ip_str_from_socket(&my_client_pool.lock().unwrap()[index]);
            if !local_ip.eq(&this_ip) {
                send_u8(&my_client_pool.lock().unwrap()[index], &msg);
            }
        }
    });

    // 消息发送
    // loop {
    //     let ins = str_utils::input();
    //     if ins.eq("exit") {
    //         return;
    //     }
    //     send_str(&write, &ins);
    // }
    let _ = t1.join();
}

// socket 读写分离
fn make_socket_split(receiver: Socket) -> (Socket, Socket) {
    let read_half = receiver.try_clone().unwrap();
    let write_half = receiver.try_clone().unwrap();
    (read_half, write_half)
}

// 发送一个字符串
pub fn send_str(writer: &Socket, str: &str) {
    let _ = writer.send(str.as_bytes());
}

// 发送一个u8
pub fn send_u8(writer: &Socket, msg: &Vec<u8>) {
    let _ = writer.send(msg);
}

// 阻塞接收 字符串
pub fn recv_str(reader: &Socket) -> String {
    let mut buf = [MaybeUninit::new(1); 1024];
    let size = reader.recv(&mut buf).unwrap();
    let mut vec = vec![];
    let _ = unsafe {
        for index in 0..size {
            vec.push(buf[index].assume_init())
        }
    };
    String::from_utf8(vec).unwrap()
}

// 阻塞接收 u8
pub fn recv_u8(reader: &Socket) -> Vec<u8> {
    let mut buf = [MaybeUninit::new(1); 1024];
    let size = reader.recv(&mut buf).unwrap();
    let mut vec = vec![];
    let _ = unsafe {
        for index in 0..size {
            vec.push(buf[index].assume_init())
        }
    };
    vec
}

// 获得 对方的ip地址
fn get_ip_str_from_socket(socket: &Socket) -> String {
    socket
        .peer_addr()
        .unwrap()
        .as_socket_ipv4()
        .unwrap()
        .to_string()
}
